<template>
  <div id="app" :class="{ dark: store.settings.theme === 'dark' }">
    <!-- 自定义标题栏 -->
    <div class="title-bar" @dblclick="toggleMaximize">
      <div class="title-bar-left">
        <img src="/icon.png" alt="App Icon" class="title-bar-icon" />
        <div class="title-bar-text">
          MarkGod
          <span v-if="store.isModified" class="unsaved-indicator">●</span>
          <span v-if="store.currentFile?.path" class="file-path">— {{ store.currentFile.path }}</span>
        </div>
      </div>
      <div class="title-bar-controls">
        <button class="title-bar-button minimize-btn" @click="minimizeWindow">
          <svg width="12" height="12" viewBox="0 0 12 12" fill="none">
            <path d="M2 6h8" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>
          </svg>
        </button>
        <button class="title-bar-button maximize-btn" @click="toggleMaximize">
          <svg width="12" height="12" viewBox="0 0 12 12" fill="none" v-if="!isMaximized">
            <rect x="2" y="2" width="8" height="8" stroke="currentColor" stroke-width="1.5" fill="none"/>
          </svg>
          <svg width="12" height="12" viewBox="0 0 12 12" fill="none" v-else>
            <rect x="2.5" y="1.5" width="6" height="6" stroke="currentColor" stroke-width="1.5" fill="none"/>
            <rect x="3.5" y="4.5" width="6" height="6" stroke="currentColor" stroke-width="1.5" fill="none"/>
          </svg>
        </button>
        <button class="title-bar-button close-button" @click="closeWindow">
          <svg width="12" height="12" viewBox="0 0 12 12" fill="none">
            <path d="M3 3l6 6M9 3l-6 6" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>
          </svg>
        </button>
      </div>
    </div>
    
    <!-- 工具栏和文件操作合并为一行 -->
    <div class="toolbar-container">
      <Toolbar :editor="editorRef" @open-settings="settingsVisible = true" />
    </div>
    
    <div class="main-content" ref="mainContentRef">
      <div
        v-if="store.showEditor"
        class="editor-container"
        :style="store.showEditor && store.showPreview
          ? { flex: `${store.settings.editorWidth} ${store.settings.editorWidth} 0` }
          : { flex: '1 1 0' }"
      >
        <Editor ref="editorRef" :style="{ fontSize: `${store.settings.fontSize}px` }" />
      </div>

      <div
        v-if="store.showEditor && store.showPreview"
        class="split-resizer"
        @mousedown="onStartResize"
        title="拖拽调整宽度"
      ></div>

      <div
        v-if="store.showPreview"
        class="preview-pane"
        :style="store.showEditor && store.showPreview
          ? { flex: `${100 - store.settings.editorWidth} ${100 - store.settings.editorWidth} 0`, overflow: 'hidden' }
          : { flex: '1 1 0', overflow: 'auto' }"
      >
        <Preview :style="{ fontSize: `${store.settings.fontSize}px` }" />
      </div>
    </div>
    <div class="app-overlay" v-if="showOverlay">
      <div class="overlay-content">
        <p>正在处理中...</p>
      </div>
    </div>

    <!-- 保存确认弹窗 -->
    <SaveConfirmDialog 
      v-model:visible="saveConfirmVisible" 
      :fileName="getFileName(store.currentFile?.path)" 
      @action="onSaveConfirmAction" 
    />
    <el-dialog v-model="settingsVisible" title="设置" width="520px" destroy-on-close>
      <SettingsPanel />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, onBeforeUnmount } from 'vue'
import { useAppStore } from './store'
import Toolbar from './components/Toolbar.vue'

import Editor from './components/Editor.vue'
import Preview from './components/Preview.vue'
import SaveConfirmDialog from './components/SaveConfirmDialog.vue'
import SettingsPanel from './components/SettingsPanel.vue'

const store = useAppStore()
const editorRef = ref<InstanceType<typeof Editor> | null>(null)
const isMaximized = ref(false)
const settingsVisible = ref(false)
const mainContentRef = ref<HTMLElement | null>(null)


// 计算属性：是否显示覆盖层
const showOverlay = computed(() => {
  return store.loading
})

// 窗口控制函数
const minimizeWindow = () => {
  window.electronAPI?.minimizeWindow?.()
}

const toggleMaximize = () => {
  window.electronAPI?.toggleMaximizeWindow?.()
  isMaximized.value = !isMaximized.value
}

const closeWindow = () => {
  window.electronAPI?.closeWindow?.()
}

// 等待组件挂载后打印调试信息
onMounted(async () => {
  console.log('App mounted, editorRef:', editorRef.value)
  // 设置初始化已在渲染入口完成，这里无需再次调用，避免重复监听
  
  // 监听窗口最大化状态变化
  window.electronAPI?.onWindowMaximized?.((event: any, maximized: boolean) => {
    isMaximized.value = maximized
  })

  // 通过文件关联事件打开文件：复用Toolbar的打开文件逻辑，但不弹选择框
  window.electronAPI?.onFileOpened?.(async (_event: any, data: { filePath: string; content: string }) => {
    try {
      const canProceed = await (window as any).appHandleUnsavedChanges?.()
      if (canProceed === false) {
        return
      }
      if (data && typeof data.filePath === 'string') {
        store.setCurrentFile(data.filePath, data.content)
        store.setModified(false)
      }
    } catch (e) {
      console.error('处理文件关联打开失败:', e)
    }
  })

  // 渲染侧就绪：通知主进程我们已注册完监听器
  window.electronAPI?.rendererReady?.()

 
  
  // 注册关闭前检查处理器
  window.electronAPI?.handleCheckBeforeClose?.(async () => {
    console.log('=== 关闭前检查处理器被调用 ===')
    console.log('当前isModified状态:', store.isModified)
    console.log('当前文件:', store.currentFile)
    console.log('编辑器内容长度:', store.editorContent?.length || 0)
    
    // 检查是否有未保存的修改
    if (store.isModified) {
      console.log('检测到未保存的修改，显示确认对话框')
      // 显示保存确认对话框
      const result = await showSaveConfirmDialog()
      console.log('用户选择:', result)
      
      if (result === 'save') {
        // 用户选择保存
        try {
          if (store.currentFile && store.currentFile.path) {
            // 保存到当前文件
            const r = await window.electronAPI?.saveFile?.(store.editorContent, store.currentFile.path)
            if (r?.success) {
              store.setModified(false)
              store.currentFile.content = store.editorContent
              return true // 允许关闭
            }
            return false
          } else {
            // 另存为新文件
            const r = await window.electronAPI?.saveFileAs?.(store.editorContent)
            if (!r?.canceled && r?.filePath) {
              store.setCurrentFile(r.filePath, store.editorContent)
              store.setModified(false)
              return true
            }
            return false
          }
        } catch (error) {
          console.error('保存文件失败:', error)
          return false // 阻止关闭
        }
      } else if (result === 'discard') {
        // 用户选择不保存，直接关闭
        return true
      } else {
        // 用户取消关闭
        return false
      }
    }
    // 没有未保存的修改，直接关闭
    console.log('没有未保存的修改，允许关闭')
    return true
  })
  
  // 注册Ctrl+S快捷键
  const handleKeyDown = (event: KeyboardEvent) => {
    if (event.ctrlKey && event.key === 's') {
      event.preventDefault()
      handleSave()
    }
  }
  
  document.addEventListener('keydown', handleKeyDown)
  
  // 清理事件监听器
  onBeforeUnmount(() => {
    document.removeEventListener('keydown', handleKeyDown)
  })
})

// 保存文件函数
 const handleSave = async () => {
   try {
     if (store.currentFile && store.currentFile.path) {
       // 保存到当前文件
       const r = await window.electronAPI?.saveFile?.(store.editorContent, store.currentFile.path)
       if (r?.success) {
         store.setModified(false)
         store.currentFile.content = store.editorContent
       } else {
         console.error('保存失败')
       }
     } else {
       // 另存为新文件
       const r = await window.electronAPI?.saveFileAs?.(store.editorContent)
       if (!r?.canceled && r?.filePath) {
         store.setCurrentFile(r.filePath, store.editorContent)
         store.setModified(false)
       } else {
         console.error('另存为失败或取消')
       }
     }
   } catch (error) {
     console.error('保存文件失败:', error)
   }
 }
 
 // 获取文件名
const getFileName = (filePath: string | null | undefined) => {
  if (!filePath || typeof filePath !== 'string') {
    return 'Untitled'
  }
  return filePath.split(/[/\\]/).pop() || 'Untitled'
}

// 显示保存确认对话框
const saveConfirmVisible = ref(false)
let resolveSaveConfirm: ((r: 'save' | 'discard' | 'cancel') => void) | null = null
const onSaveConfirmAction = (r: 'save' | 'discard' | 'cancel') => {
  saveConfirmVisible.value = false
  if (resolveSaveConfirm) {
    resolveSaveConfirm(r)
    resolveSaveConfirm = null
  }
}

const showSaveConfirmDialog = (): Promise<'save' | 'discard' | 'cancel'> => {
  return new Promise((resolve) => {
    resolveSaveConfirm = resolve
    saveConfirmVisible.value = true
  })
}

// 通用的保存确认处理函数，供其他组件调用
const handleUnsavedChanges = async (): Promise<boolean> => {
  console.log('=== 检查未保存的修改 ===')
  console.log('当前isModified状态:', store.isModified)
  
  // 检查是否有未保存的修改
  if (store.isModified) {
    console.log('检测到未保存的修改，显示确认对话框')
    // 显示保存确认对话框
    const result = await showSaveConfirmDialog()
    console.log('用户选择:', result)
    
    if (result === 'save') {
      // 用户选择保存
      try {
        if (store.currentFile && store.currentFile.path) {
          // 保存到当前文件
          const r = await window.electronAPI?.saveFile?.(store.editorContent, store.currentFile.path)
          if (r?.success) {
            store.setModified(false)
            store.currentFile.content = store.editorContent
            return true // 允许继续操作
          }
          return false
        } else {
          // 另存为新文件
          const r = await window.electronAPI?.saveFileAs?.(store.editorContent)
          if (!r?.canceled && r?.filePath) {
            store.setCurrentFile(r.filePath, store.editorContent)
            store.setModified(false)
            return true
          }
          return false
        }
      } catch (error) {
        console.error('保存文件失败:', error)
        return false // 阻止操作
      }
    } else if (result === 'discard') {
      // 用户选择不保存，继续操作
      return true
    } else {
      // 用户取消操作
      return false
    }
  }
  
  // 没有未保存的修改，可以继续操作
  return true
}

// 将函数暴露给全局，供其他组件使用
window.appHandleUnsavedChanges = handleUnsavedChanges

// ==================== 分割条拖拽调整宽度 ====================
let isResizing = false
let startX = 0
let containerRect: DOMRect | null = null

const clamp = (val: number, min: number, max: number) => Math.max(min, Math.min(max, val))

const onStartResize = (e: MouseEvent) => {
  if (!mainContentRef.value) return
  isResizing = true
  startX = e.clientX
  containerRect = mainContentRef.value.getBoundingClientRect()
  document.body.style.cursor = 'col-resize'
  document.body.style.userSelect = 'none'
  window.addEventListener('mousemove', onResizing)
  window.addEventListener('mouseup', onStopResize)
}

const onResizing = (e: MouseEvent) => {
  if (!isResizing || !containerRect) return
  const relativeX = e.clientX - containerRect.left
  const widthPercent = clamp(Math.round((relativeX / containerRect.width) * 100), 20, 80)
  // 仅在双栏显示时生效
  if (store.showEditor && store.showPreview) {
    store.updateEditorWidth(widthPercent)
  }
}

const onStopResize = () => {
  isResizing = false
  containerRect = null
  document.body.style.cursor = ''
  document.body.style.userSelect = ''
  window.removeEventListener('mousemove', onResizing)
  window.removeEventListener('mouseup', onStopResize)
}
</script>

<style>
/* 全局样式 - 不使用scoped */
#app {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
  color: #2c3e50;
  height: 100vh;
  display: flex;
  flex-direction: column;
  transition: background-color 0.3s ease, color 0.3s ease;
  position: relative;
  overflow: hidden;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

/* 确保body和html没有滚动条 */
html, body {
  margin: 0;
  padding: 0;
  height: 100%;
  overflow: hidden;
}

/* 局部样式 - 使用scoped */
</style>

<style scoped>

/* 自定义标题栏 */
.title-bar {
  height: 32px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 15px;
  -webkit-app-region: drag; /* 使标题栏可拖拽 */
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  flex-shrink: 0;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.title-bar-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.title-bar-text {
  font-size: 14px;
  font-weight: 600;
  color: #ffffff;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
  letter-spacing: 0.5px;
  display: flex;
  align-items: center;
  gap: 8px;
  min-width: 0; /* 允许子元素收缩 */
  height: 32px; /* 与标题栏等高 */
}

.title-bar-icon {
  height: 20px; /* 与标题栏等高 */
  width: auto;
  display: inline-block;
  vertical-align: middle;
  margin-right: 6px;
  filter: drop-shadow(0 1px 1px rgba(0,0,0,0.2));
  pointer-events: none;
  object-fit: contain;
  -webkit-app-region: no-drag;
}

.unsaved-indicator {
  color: #ff6b6b;
  font-size: 16px;
  font-weight: bold;
  text-shadow: 0 0 4px rgba(255, 107, 107, 0.5);
  animation: pulse 2s infinite;
}

.file-name {
  color: rgba(255, 255, 255, 0.8);
  font-weight: 400;
  font-size: 13px;
}

@keyframes pulse {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: 0.6;
  }
}

.title-bar-controls {
  display: flex;
  -webkit-app-region: no-drag; /* 按钮区域不可拖拽 */
  gap: 2px;
}

.title-bar-button {
  width: 32px;
  height: 24px;
  border: none;
  background: transparent;
  font-size: 12px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #ffffff;
  transition: all 0.2s ease;
  border-radius: 4px;
}

.title-bar-button svg {
  transition: color 0.2s ease;
}

.title-bar-button:hover {
  background-color: rgba(255, 255, 255, 0.15);
  transform: scale(1.05);
}

.close-button:hover {
  background-color: #ff5555;
  color: white;
}

.close-button:hover svg {
  color: white;
}

/* 工具栏和文件操作容器 */
.toolbar-container {
  display: flex;
  align-items: center;
  padding: 8px 15px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.08);
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  flex-shrink: 0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.main-content {
  flex: 1;
  display: flex;
  overflow: hidden;
  height: calc(100vh - 72px); /* 减去标题栏和工具栏的高度 */
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  margin: 8px;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.editor-container {
  border-right: 1px solid rgba(0, 0, 0, 0.08);
  display: flex;
  flex-direction: column;
  overflow: hidden;
  transition: all 0.3s ease;
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(10px);
}

.editor-container > * {
  flex: 1 1 auto;
  min-height: 0; /* 允许内部产生滚动条 */
}

.preview-pane {
  display: flex;
  flex-direction: column;
  overflow: hidden;
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(10px);
}

.preview-pane > * {
  flex: 1 1 auto;
  min-height: 0; /* 允许预览根容器在单栏时出现滚动条 */
}

.split-resizer {
  width: 8px;
  cursor: col-resize;
  background: linear-gradient(180deg, rgba(102, 126, 234, 0.35) 0%, rgba(118, 75, 162, 0.35) 100%);
  transition: background 0.2s ease;
}

.split-resizer:hover {
  background: linear-gradient(180deg, rgba(102, 126, 234, 0.6) 0%, rgba(118, 75, 162, 0.6) 100%);
}

.app-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.6);
  backdrop-filter: blur(5px);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.overlay-content {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
  padding: 30px 40px;
  border-radius: 16px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.2);
  text-align: center;
  border: 1px solid rgba(255, 255, 255, 0.3);
}

.overlay-content p {
  margin: 0;
  font-size: 16px;
  color: #333;
  font-weight: 500;
}

/* 暗色主题 */
#app.dark {
  background: linear-gradient(135deg, #1a1a2e 0%, #16213e 50%, #0f3460 100%);
  color: #e1e5e9;
}

#app.dark .title-bar {
  background: linear-gradient(135deg, #2d3748 0%, #1a202c 100%);
  border-bottom-color: rgba(255, 255, 255, 0.1);
}

#app.dark .title-bar-text {
  color: #e1e5e9;
}

#app.dark .title-bar-button {
  color: #e1e5e9;
  background: transparent;
}

#app.dark .title-bar-button svg {
  color: #e1e5e9;
}

#app.dark .title-bar-button:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

#app.dark .close-button:hover svg {
  color: white;
}

#app.dark .close-button:hover {
  background-color: #ff5555;
}

#app.dark .toolbar-container {
  background: rgba(45, 55, 72, 0.95);
  backdrop-filter: blur(10px);
  border-bottom-color: rgba(255, 255, 255, 0.1);
}

#app.dark .main-content {
  background: rgba(26, 32, 44, 0.9);
  backdrop-filter: blur(10px);
  border-color: rgba(255, 255, 255, 0.1);
}

#app.dark .editor-container {
  border-right-color: rgba(255, 255, 255, 0.1);
  background: rgba(26, 32, 44, 0.8);
  backdrop-filter: blur(10px);
}

#app.dark .preview-pane {
  background: rgba(26, 32, 44, 0.8);
  backdrop-filter: blur(10px);
}

#app.dark .split-resizer {
  background: linear-gradient(180deg, rgba(76, 81, 191, 0.35) 0%, rgba(85, 60, 154, 0.35) 100%);
}

#app.dark .split-resizer:hover {
  background: linear-gradient(180deg, rgba(76, 81, 191, 0.6) 0%, rgba(85, 60, 154, 0.6) 100%);
}

#app.dark .overlay-content {
  background: rgba(45, 55, 72, 0.95);
  backdrop-filter: blur(20px);
  color: #e1e5e9;
  border-color: rgba(255, 255, 255, 0.2);
}

/* 添加一些动画效果 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.main-content {
  animation: fadeIn 0.5s ease-out;
}

/* 滚动条美化 */
::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

::-webkit-scrollbar-track {
  background: rgba(0, 0, 0, 0.05);
  border-radius: 4px;
}

::-webkit-scrollbar-thumb {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 4px;
  transition: all 0.3s ease;
}

::-webkit-scrollbar-thumb:hover {
  background: linear-gradient(135deg, #5a67d8 0%, #6b46c1 100%);
}

#app.dark ::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.05);
}

#app.dark ::-webkit-scrollbar-thumb {
  background: linear-gradient(135deg, #4a5568 0%, #2d3748 100%);
}

#app.dark ::-webkit-scrollbar-thumb:hover {
  background: linear-gradient(135deg, #718096 0%, #4a5568 100%);
}
.file-path {
  color: rgba(255, 255, 255, 0.85);
  font-weight: 500;
  font-size: 12px;
  max-width: 50vw;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>